import React from 'react';
import { useDispatch, useSelector } from 'dva';
import { Alert } from 'antd';
import { createAction } from '@/utils';
import Login from '@/components/Login';

import styles from './index.less';

const { UserName, Password, Submit } = Login;

const LoginPage = props => {
  const dispatch = useDispatch()

  const { 
    error
  } = useSelector(_ => _.login)

  const { effects } = useSelector(_ => _.loading)
  const loading = effects['login/login']

  const handleSubmit = (err, values) => {
    if (!err) {
      dispatch(createAction('login/login')({
        ...values,
      }));
    }
  };
  const renderMessage = message => (
    <Alert style={{ marginBottom: 20 }} message={message} type="error" showIcon />
  );

  let loginForm

  return (
    <div className={styles.main}>
      <Login
        onSubmit={handleSubmit}
        ref={form => {
          loginForm = form;
        }}
      >
        {error && error.message && !loading && renderMessage(error.message)}
        <UserName
          name="name"
          onPressEnter={e => {
            e.preventDefault();
            loginForm.validateFields(handleSubmit);
          }}
        />
        <Password
          name="pwd"
          onPressEnter={e => {
            e.preventDefault();
            loginForm.validateFields(handleSubmit);
          }}
        />
        <Submit className={styles.button} loading={loading}>登录</Submit>
      </Login>
    </div>
  );
}

export default LoginPage;
